<?php
namespace Admin\Model;

class ContractModel extends \Think\Model
{
	//自动验证
	protected $_validate = array(
		array('code','/^\w{6,}$/', '请输入正确的合同代码', 1),
		array('name', '/^[\w\x{4e00}-\x{9fa5}]{2,}$/u', '请输入正确的合同名称', 1),
		array('title', '/^[\w\x{4e00}-\x{9fa5}]{2,}$/u', '请输入正确的合同标题', 1),
		array('content', 'require', '请输入合同内容', 1),
		array('update_note', 'require', '请输入更新说明', 1, 'regex', 2),
		array('type','/^[1-9]\d*$/', '请应选择合同类型', 1),
	);
	
	//自动完成
	protected $_auto = array(
		array('status', '1'),
		array('create_time', 'time', 1, 'function'),
		array('update_time', 'time', 3, 'function'),
	);
	
	/**
	 * 添加合同
	 * @author 刘新
	 */
	public function addContract()
	{
		//创建为数据对象
		$res = $this->create();
		if(!$res) return array('error' => 1, 'msg' => $this->getError());
		$admin = session('user_auth');
		$this->admin_id = $admin['uid'];
		$this->admin_name = $admin['username'];
		$return = array('error' => 0, 'msg' => '添加成功');
		//开启事务
		$this->startTrans();
		try {
			//添加合同
			$res = $this->add();
			
			if(!$res) {
				throw new \Think\Exception('合同添加失败');
			}

			//添加合同日志
			$data['contract_id'] = $res;
			$data['admin_id'] = $admin['uid'];
			$data['admin_name'] = $admin['username'];
			$data['admin_note'] = '新增合同';
			$data['create_time'] = time();
			$data['update_time'] = time();
			$data['status'] = 1;
			$res = M('ContractLog')->add($data);

			//如果日志出错，记录
			if(!$res) {
				throw new \Think\Exception('合同日志添加失败');
			} 
			
			$this->commit();
		} catch (\Think\Exception $e) {
			$this->rollback();
			$return['error'] = 1;
			$return['msg'] = $e->getMessage();
		}
		
		return $return;
	}

	/**
	 * 编辑合同
	 * @author 刘新
	 */
	public function editContract()
	{
		//创建为数据对象
		$res = $this->create();
		if(!$res) return array('error' => 1, 'msg' => $this->getError());
		$return = array('error' => 0, 'msg' => '添加成功');
		//开启事务
		$this->startTrans();
		try {
			//添加合同
			$res = $this->save();
			filewrite("/www/webroot/nginx/Fund/Application/Home/View/Contract/".$_POST['code'].".html",$_POST['content']);
			if(!$res) {
				throw new \Think\Exception('合同编辑失败');
			}

			//添加合同日志
			$admin = session('user_auth');
			$data['contract_id'] = I('id');
			$data['admin_id'] = $admin['uid'];
			$data['admin_name'] = $admin['username'];
			$data['admin_note'] = I('update_note');
			$data['create_time'] = time();
			$data['update_time'] = time();
			$data['status'] = 1;
			$res = M('ContractLog')->add($data);
	
			//如果日志出错，记录
			if(!$res) {
				throw new \Think\Exception('合同日志添加失败');
			}
			
			//更新基金表中的合同名称
			$res = M('Fund')->where(array('contract_id'=>I('id')))->save(array('contract_name' => I('name')));
			if($res === false) {
				throw new \Think\Exception(M('Fund')->getDbError());
			}
			
			$this->commit();
		} catch (\Think\Exception $e) {
			$this->rollback();
			$return['error'] = 1;
			$return['msg'] = $e->getMessage();
		}
	
		return $return;
	}
}